package ast.stmt;

import ts.SymbolTable;
import icg.EQIdent;
import icg.EQLabel;
import icg.EQLiteral;
import icg.Quadruple;
import ast.Node;
import ast.exp.Expression;
import ast.type.Type;

public class AssignStmt extends Statement {
	private Integer id;
	private Expression exp;

	public AssignStmt(Integer id, Expression exp) {
		this.id = id;
		this.exp = exp;
	}

	@Override
	public String toString() {
		return "<AssignStmt id=\"" + id + "\">\n" + exp + "\n</AssignStmt>";
	}

	@Override
	public void typeCheck(Type type) {
		Type typeId = Node.st.getInfo(id).getType();
		Type typeExp = exp.typeCheck();
		if (typeExp != Type.ERROR && typeId != Type.ERROR)
			if (typeExp != typeId) {
				System.out.println("invalid types in assignment");
				SymbolTable.errors++;
			}
	}

	@Override
	public void genCode() {
		
		if (Node.st.getInfo(id).getType() == Type.BOOLEAN) {
			this.exp.trueL = EQLabel.FALL;
			exp.falseL = new EQLabel();
			exp.genCode();
			Node.icg.gen(Quadruple.copy(new EQIdent(id.toString()), new EQLiteral("1")));
			EQLabel l = new EQLabel();
			Node.icg.gen(Quadruple.jump(l));
			EQLabel.useLabel(exp.falseL);
			Node.icg.gen(Quadruple.copy(new EQIdent(id.toString()), new EQLiteral("0")));
			EQLabel.useLabel(l);
			
		} else {
			exp.genCode();
			Node.icg.gen(Quadruple.copy(new EQIdent(id.toString()), exp.addr));
		}
	}
}
